#include<iostream>
#include<mysql/mysql.h>

//const std::string host="127.0.0.1";
const std::string host="localhost";
const std::string user= "xiaoliu";
const std::string password= "Liuty0125";
const std::string db= "conn";
const unsigned int port=8080;

int main()
{
    //std::cout<<mysql_get_client_info()<<std::endl;
    MYSQL* my=mysql_init(nullptr);

    //1.初始化
    if(my==nullptr)
    {
        std::cerr<<"init error"<<std::endl;
        return 1;
    }

    //2.连接
    if(mysql_real_connect(my,host.c_str(),user.c_str(),password.c_str(),db.c_str(),port,nullptr,0)==nullptr)
    {
        std::cerr<<"connect error"<<std::endl;
        return 2;
    }
    //3.命令
    std::string sql="select * from users";
    int n=mysql_query(my,sql.c_str());
    if(n==0)
    {
        std::cout<<"query "<<sql<<" success"<<std::endl;
    }
    else
    {
        std::cerr<<"query "<<sql<<" error"<<std::endl;
        return 3;
    }

    //4.结果
    MYSQL_RES* res = mysql_store_result(my);
    if(res==nullptr)
    {
        std::cerr<<"store result error"<<std::endl;
        return 4;
    }

    int rows=mysql_num_rows(res);
    int fields = mysql_num_fields(res);

    std::cout<<"rows:"<<rows<<" fields:"<<fields<<std::endl;

    //属性
    MYSQL_FIELD *fields_array = mysql_fetch_fields(res);
    for(int i=0;i<fields;i++)
    {
        std::cout<<fields_array[i].name<<"\t";
    }
    std::cout<<std::endl;

    //数据
    for(int i=0;i<rows;i++)
    {
        MYSQL_ROW row = mysql_fetch_row(res);
        for(int j=0;j<fields;j++)
        {
            std::cout<<row[j]<<"\t";
        }
        std::cout<<std::endl;
    }
    // std::string sql;
    // while(true)
    // {
    //     if(!std::getline(std::cin,sql)) break;
    //     if(sql=="quit") break;

    //     int n=mysql_query(my,sql.c_str());
    //     if(n==0)
    //     {
    //         std::cout<<"query "<<sql<<" success"<<std::endl;
    //     }
    //     else
    //     {
    //         std::cerr<<"query "<<sql<<" error"<<std::endl;
    //     }
    // }

    // std::cout<<"connect mysql success"<<std::endl;


    mysql_close(my);
    return 0;
}
